import axios from "axios";
// import store from "@/store";
import { Message, deepTrim, loginOut } from "@/utils";
import router from "@/router";
import { addPendingRequest, removePendingRequest } from "./repeatedValidate";

const baseURL = process.env.VUE_APP_BASE_URL;

// axios 实例默认配置
const serviceDefaultConfig = {
  baseURL, // url = base url + request url
  timeout: 60000, // request timeout
  // withCredentials: true,
  headers: {
    "Content-Type": "application/json",
    "Cache-Control": "no-cache",
    Pragma: "no-cache",
  },
};

function serviceGenerator(serviceConfig = serviceDefaultConfig) {
  // 构造
  const service = axios.create(serviceConfig);
  // --------------------- request-interceptors ----------------------- //

  service.interceptors.request.use((config) => {
    // 添加 auth token
    // const token = store.state.authStore.userInfo?.authtoken;
    const token = localStorage.getItem("userinfo")
      ? JSON.parse(localStorage.getItem("userinfo")).authToken
      : "";
    if (token) {
      config.headers["authToken"] = token;
    }
    // 上传文件时更改 Content-Type
    if (config.params && config.params.crm_service_http_type == "upload") {
      config.method = "post";
      config.headers["Content-Type"] = "multipart/form-data";
    }
    return config;
  });

  service.interceptors.request.use((config) => {
    removePendingRequest(config);
    addPendingRequest(config);
    return config;
  });

  service.interceptors.request.use((config) => {
    const keys = ["data", "params"];

    keys.forEach((key) => {
      if (config[key] && config[key].toString() === "[object Object]") {
        config[key] = deepTrim(config[key]);
      }
    });

    return config;
  });

  // --------------------- request-response ----------------------- //

  service.interceptors.response.use(
    (response) => {
      removePendingRequest(response.config);
      // 检查 body code
      if (response.status !== 200) {
        return Promise.reject(new Error(response.message || "Error"));
      }
      // 返回 body
      return response.data;
    },
    // 异常处理
    (error) => {
      Message.closeAll();
      if (error.response) {
        const data = error.response;
        //尚未登录
        if ([480, 481, 482, 483, 484, 485].indexOf(data.status) > -1) {
          Message.warning("登录信息不匹配，请重新登录！");
          localStorage.clear();
          router.push("/index");
          // store.commit("authStore/updateUserInfo", null); // FIXME 未清除
          loginOut();
        } else if (data.status == 486) {
          Message.warning("无权操作！");
          router.push({ path: "/403" });
        } else {
          Message.error("系统错误，请稍候再试！");
        }
      } else {
        if (axios.isCancel(error)) {
          console.log("已取消的重复请求：" + error.message);
        } else {
          Message.error("系统错误，请稍候再试！");
        }
      }
      removePendingRequest(error.config || {});
      return Promise.reject(error);
    }
  );

  return service;
}

export const service = serviceGenerator();
export default serviceGenerator;
